package home.action;

import home.model.Logs;
import home.model.PageBean;
import home.model.Users;
import home.model.minUsers;
import home.service.LogService;

import java.io.PrintWriter;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

public class LogAction extends ActionSupport{
	private LogService logs;
	public LogService getLogs() {
		return logs;
	}
	public void setLogs(LogService logs) {
		this.logs = logs;
	}
	public List<Logs> getLogList() {
		return logList;
	}
	public void setLogList(List<Logs> logList) {
		this.logList = logList;
	}
	private List<Logs> logList;
	public String execute() throws Exception{
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpServletResponse response = ServletActionContext.getResponse();
		HttpSession session = request.getSession();
		Users users = (Users) session.getAttribute("users");
		String username = users.getUsername();
	    
	    pageBean = logs.getLogByUsername(page, username);
		logList = pageBean.getList();
		System.out.println(pageBean + " + " + username);
		return SUCCESS;
	}
	private int page;
	public int getPage() {
		return page;
	}
	public void setPage(int page) {
		this.page = page;
	}
	public PageBean getPageBean() {
		return pageBean;
	}
	public void setPageBean(PageBean pageBean) {
		this.pageBean = pageBean;
	}
	private PageBean pageBean;
	private String feedback;
	public String getFeedback() {
		return feedback;
	}
	public void setFeedback(String feedback) {
		this.feedback = feedback;
	}
	public String addFeedback() throws Exception{
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpServletResponse response = ServletActionContext.getResponse();
		HttpSession session = request.getSession();
		response.setCharacterEncoding("utf-8");
		response.setContentType("application/json");
		
		PrintWriter out  = response.getWriter();

		Users users = (Users) session.getAttribute("users");
		addLog(users.getUsername(), users.getName() + ":" + feedback, "feedback");
		
        JSONObject jsonO = new JSONObject();  
        jsonO.put("result","true");  
	    
		out.print(jsonO);
		out.flush();
		out.close();
		return SUCCESS;
	}
	
	public void addLog(String usersName, String logContent, String logType){
		Logs log = new Logs();
		log.setType(logType);
		log.setUsers_name(usersName);
		log.setContent(logContent);
		
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date=new Date(System.currentTimeMillis());
		log.setCreated_at(df.format(date));
		log.setCreated_by("MsgMngAction/addSubmit");
		log.setUpdated_at(df.format(date));
		log.setUpdated_by("MsgMngAction/addSubmit");
		
		logs.saveLog(log);
	}
}
